<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class BlacklistController
 * @package Wintel\RestBundle\Controller
 */
class BlacklistController extends Controller
{
    /**
     * 添加黑名单
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function blacklistAddAction(Request $request)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        $vcc_id = $request->get('vcc_id', 0);
        $phones = $request->get('phones', '');
        $phone_type = $request->get('phone_type', 1);
        $trunk_num = $request->get('trunk_num', '');

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空'
            );

            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 405,
                'message' => '企业ID为非数字'
            );

            return new JsonResponse($ret);
        }

        if (empty($phones)) {
            $ret = array(
                'code' => 402,
                'message' => '号码为空'
            );

            return new JsonResponse($ret);
        }

        if (!is_string($phones)) {
            $ret = array(
                'code' => 406,
                'message' => '号码格式不对，要求为多个号码逗号分隔的字符串，但是得到'.gettype($phones)
            );

            return new JsonResponse($ret);
        }

        if (!empty($trunk_num)) {
            //查看中继号是否存在
            $count = $conn->fetchColumn(
                'SELECT count(*) FROM cc_phone400s WHERE vcc_id = :vcc_id AND phone = :phone ',
                array('vcc_id'=>$vcc_id, 'phone'=>$trunk_num)
            );
            if ($count <= 0) {
                return new JsonResponse(array('code'=>408, 'message'=>'中继号码不存在'));
            }
        }

        $conn->beginTransaction();
        $phonesArray = explode(',', $phones);
        $resData = array();
        foreach ($phonesArray as $phone) {
            switch ($phone_type) {
                case '1'://固定号码
                    if (!is_numeric($phone)) {
                        $ret = array(
                            'code' => 403,
                            'message' => '固定号码中包含非数字字符'
                        );

                        return new JsonResponse($ret);
                    }
                    break;
                case '2'://模糊匹配
                    if (!preg_match('/^[\*0-9]+?$/', $phone)) {
                        $ret = array(
                            'code' => 407,
                            'message' => '模糊匹配号码中包含除*外的非数字字符'
                        );

                        return new JsonResponse($ret);
                    }
                    break;
                default:
                    break;
            }

            $data = array(
                'vcc_id' => $vcc_id,
                'phone_num' => $phone,
                'black_type' => $phone_type,
                'trunk_num' => $trunk_num
            );
            $conn->insert('cc_blacklist', $data);
            $lastId = $conn->lastInsertId();
            $resData[$lastId] = $phone;
        }

        try {
            $conn->commit();

            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data'=>$resData
            );

            return new JsonResponse($ret);

        } catch (Exception $e) {
            $conn->rollback();

            $ret = array(
                'code' => 404,
                'message' => '添加黑名单失败['.$e->getMessage().']'
            );

            return new JsonResponse($ret);
        }
    }

    /**
     * 删除黑名单
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function blacklistDeleteAction(Request $request)
    {
        $vcc_id = $request->get('vcc_id', 0);
        $phone_ids = $request->get('phone_ids', '');

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空'
            );

            return new JsonResponse($ret);
        }

        if (!is_numeric($vcc_id)) {
            $ret = array(
                'code' => 405,
                'message' => '企业ID包含非数字字符'
            );

            return new JsonResponse($ret);
        }

        if (empty($phone_ids)) {
            $ret = array(
                'code' => 402,
                'message' => '号码ID为空'
            );

            return new JsonResponse($ret);
        }

        if (!is_string($phone_ids)) {
            $ret = array(
                'code' => 406,
                'message' => '号码ID格式不对，要求为多个号码ID逗号分隔的字符串，但是得到'.gettype($phone_ids)
            );

            return new JsonResponse($ret);
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        $conn->beginTransaction();
        $phonesArray = explode(',', $phone_ids);
        foreach ($phonesArray as $phone_id) {
            if (!is_numeric($phone_id)) {
                $ret = array(
                    'code' => 403,
                    'message' => '号码ID中包含非数字字符'
                );

                return new JsonResponse($ret);
            }

            $data = array(
                'vcc_id' => $vcc_id,
                'id' => $phone_id,
            );

            $conn->delete('cc_blacklist', $data);
        }

        try {
            $conn->commit();

            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );

            return new JsonResponse($ret);

        } catch (Exception $e) {
            $conn->rollback();

            $ret = array(
                'code' => 404,
                'message' => '删除黑名单失败['.$e->getMessage().']'
            );

            return new JsonResponse($ret);
        }
    }

    /**
     * 查询黑名单
     *
     * @param $info
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function blacklistListAction($info)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }
        if (!isset($addInfo['vcc_code'])) {
            return new JsonResponse(array('code'=> 404, 'message'=>'json中没有vcc_code'));
        }
        $vcc_code = $addInfo['vcc_code'];
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        $where = '';
        if (isset($addInfo['filter'])) {
            $where = isset($addInfo['filter']['phone']) && !empty($addInfo['filter']['phone']) ?
                " AND phone_num  like '%".$addInfo['filter']['phone']."%' " : '';
        }
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM cc_blacklist '.
            'WHERE vcc_id = :vid '.$where,
            array('vid'=>$vid)
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'cc_blacklist', $addInfo);
        $data = $conn->fetchAll(
            "SELECT id,vcc_id,phone_num,black_type,trunk_num FROM cc_blacklist WHERE vcc_id= :vid ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vid'=>$vid)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $data
        );

        return new JsonResponse($ret);
    }
}
